package com.bw.solr.solr05spellcheck;

import java.util.ArrayList;
import java.util.List;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.SpellCheckResponse;
import org.apache.solr.client.solrj.response.SpellCheckResponse.Collation;
import org.apache.solr.client.solrj.response.SpellCheckResponse.Suggestion;

/**
 * 拼写检查代码演示
 *
 */

public class SpellcheckTest {

	public static void main(String[] args) throws SolrServerException {

		String solrUrl = "http://localhost:28080/solr/mycore2";

		HttpSolrClient client = new HttpSolrClient(solrUrl);

		String token = "王麻字";

		SolrQuery query = new SolrQuery("student_name:" + token);

		query.setParam("qt", "/spell");

		query.set("spellcheck", "true");
		query.setParam("spellcheck.collate","true");
		
		
		System.out.println(query.toString());
		
		QueryResponse checkResponse = client.query(query);

		SpellCheckResponse spellCheckResponse = checkResponse
				.getSpellCheckResponse();
		List<Suggestion> suggestions = spellCheckResponse.getSuggestions();

		List<String> result = new ArrayList<String>();
		for (Suggestion suggestion : suggestions) {
			// int numFound = suggestion.getNumFound();
			// System.out.println(numFound);
			List<String> alternatives = suggestion.getAlternatives();
			for (String string : alternatives) {
				System.out.println(string);
				result.add(string);
			}
		}
		int numFound = result.size();// 纠错词个数

		System.out.println("查询耗时：" + checkResponse.getQTime());
		
		List<Collation> collatedResults = spellCheckResponse.getCollatedResults();
	    for (Collation collation : collatedResults) {  
	       System.out.println(collation.getCollationQueryString());   
	    }

	}

}
